package com.tianyu.service.mqtt.handler.inbound;

import com.alibaba.fastjson2.JSON;
import com.tianyu.service.mqtt.common.MqttMessageChannel;
import com.tianyu.service.mqtt.common.SpringBeanUtils;
import com.tianyu.service.mqtt.model.enums.TopicEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.annotation.Router;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.integration.router.AbstractMessageRouter;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Collections;
import java.util.Objects;


/**
 * @author swyan
 */
@Component
@Slf4j
public class InboundMessageRouter extends AbstractMessageRouter {

    @Bean
    public IntegrationFlow mqttInboundFlow() {
        return IntegrationFlow.from(MqttMessageChannel.ChannelName.INBOUND)
                .channel(MqttMessageChannel.ChannelName.INBOUND_ROUTE)
                .get();
    }

    @Override
    @Router(inputChannel = MqttMessageChannel.ChannelName.INBOUND_ROUTE)
    protected Collection<MessageChannel> determineTargetChannels(Message<?> message) {
        MessageHeaders headers = message.getHeaders();
        String topic = Objects.requireNonNull(headers.get(MqttHeaders.RECEIVED_TOPIC)).toString();
        TopicEnum topicEnum = TopicEnum.find(topic);
        // log.info(topicEnum.getBeanName());
        MessageChannel bean = (MessageChannel) SpringBeanUtils.getBean(topicEnum.getBeanName());
        return Collections.singleton(bean);
    }

}
